﻿using Entity;
using PlanWater.Helper;
using PlanWater.Helper.Entity;
using Platform.Data;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PlanWater.AutoApproveNo
{

    /// <summary>
    /// 获取图片助手
    /// 单例模式
    /// </summary>
    public class GongShuiChuImageHandler
    {
        public GongShuiChuImageHandler()
        {
            QRCodeURL = System.Configuration.ConfigurationManager.AppSettings["QRCodeURL"];
            BarCodeURL = System.Configuration.ConfigurationManager.AppSettings["BarCodeURL"];
            SaveQRCodeImgPath = System.Configuration.ConfigurationManager.AppSettings["SaveQRCodeImgPath"];
            SaveBarCodeImgPath = System.Configuration.ConfigurationManager.AppSettings["SaveBarCodeImgPath"];
        }
        #region 属性变量 

        private string QRCodeURL;
        private string BarCodeURL;
        private string SaveQRCodeImgPath;
        private string SaveBarCodeImgPath;
        /// <summary>
        /// 处理队列
        /// </summary>
        private Queue<YS_LH_LAIHANXX> _HandlerData = new Queue<YS_LH_LAIHANXX>();
        private static Dictionary<eLaiHanLX, string> LxDict = new Dictionary<eLaiHanLX, string> {
                { eLaiHanLX.月度,"0100540003" },
                { eLaiHanLX.计划转移,"0100540002" },
                { eLaiHanLX.基建调整,"0100540001" },
                { eLaiHanLX.年度,"0100540005" },
                { eLaiHanLX.计划变更,"0100540004" }
        };
        #endregion
         
        #region 方法

        #region 私有方法
        /// <summary>
        /// 处理图片
        /// </summary>
        private string HandleImage(string url, string savePath, string saveName)
        {
            string filePath = string.Empty;
            var stream = PictureHelper.GetImageStream(url);
            if (null != stream)
            {
                PictureHelper.SaveImage(stream, savePath, saveName, out filePath);
            }
            return filePath;
        }

        /// <summary>
        /// 获取拼接URL
        /// </summary>
        /// <param name="type"></param>
        /// <param name="unicode"></param>
        /// <param name="applicateName"></param>
        /// <returns></returns>
        private string GetURL(图片类型 type, string unicode, string applicateName)
        {
            string url = string.Empty;
            if (type == 图片类型.二维码)
            {
                url = string.Format(QRCodeURL, unicode, applicateName);
            }
            else if (type == 图片类型.条形码)
            {
                url = string.Format(BarCodeURL, unicode);
            }
            return url;
        }

        /// <summary>
        /// 获取图片路径
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private string GetSavePath(图片类型 type)
        {
            string path = string.Empty;
            if (type == 图片类型.二维码)
            {
                path =  SaveQRCodeImgPath;
            }
            else
            {
                path = SaveBarCodeImgPath;
            }

            return path;
        }

        /// <summary>
        /// 获取二维码
        /// </summary>
        /// <param name="applicateName"></param>
        /// <param name="uniCode"></param>
        /// <returns></returns>
        private string GetQRCode(string applicateName, string uniCode, out string fileName)
        {
            fileName = string.Format("Q{0}{1}", uniCode, System.DateTime.Now.ToString("yyyyMMddHHmmss"));
            string path = HandleImage(GetURL(图片类型.二维码, uniCode, applicateName), GetSavePath(图片类型.二维码), fileName);
            return path;
        }

        /// <summary>
        /// 获取条形码
        /// </summary>
        /// <param name="applicateName"></param>
        /// <param name="uniCode"></param>
        /// <returns></returns>
        private string GetBarCode(string applicateName, string uniCode, out string fileName)
        {
            fileName = string.Format("B{0}{1}", uniCode, System.DateTime.Now.ToString("yyyyMMddHHmmss"));
            string path = HandleImage(GetURL(图片类型.条形码, uniCode, applicateName), GetSavePath(图片类型.条形码), fileName);
            return path;

        }

        /// <summary>
        /// 获取数据
        /// </summary>
        private void GetData()
        {
            LogHelper.Instance.Log("查询来函数据");
            string sql = @"select t.id,t.s_laihanbh,t.i_laihanlx,t.S_YONGHUM from YS_LH_LAIHANXX t
where t.s_tongyibm is null and t.i_y>2017 and t.i_laihanlx in(1,2,3,5,6) and t.I_LIUCHENGZT>-1";
            var dr= OracleHelper.ExecuteReader(GetConn(), CommandType.Text, sql);
            while (dr.Read())
            {
                YS_LH_LAIHANXX entity = new YS_LH_LAIHANXX();
                entity.ID=decimal.Parse( dr["id"].ToString());
                entity.S_LAIHANBH = dr["s_laihanbh"].ToString();
                entity.S_YONGHUM = dr["S_YONGHUM"].ToString();
                entity.I_LAIHANLX = decimal.Parse(dr["i_laihanlx"].ToString()); 
                _HandlerData.Enqueue(entity);
            }
         
        }


        string _Conn = null;
        private string GetConn()
        {
            if (string.IsNullOrEmpty(_Conn))
            {
                _Conn = System.Configuration.ConfigurationManager.ConnectionStrings["AppDbContext"].ConnectionString;

            }
            return _Conn;
        }

        private bool CheckSaveData(YS_LH_LAIHANXX entity)
        {
            //bool flag = true;
            //if (flag&&string.IsNullOrEmpty(entity.UniCode))
            //{
            //    LogHelper.Instance.Log("获取统一编码失败！");
            //    flag = false;
            //}
            //if(f)

            return false;
        }

        #endregion

        #region 公共方法
        /// <summary>
        /// 处理方法
        /// </summary>
        public void Handle()
        {
            GetData();//查询数据
            while (_HandlerData.Count > 0)
            {
                try
                {
                    var data = _HandlerData.Dequeue();
                    LogHelper.Instance.Log(string.Format("来函编号：{0}，开始处理数据", data.S_LAIHANBH));
                    if (string.IsNullOrEmpty(data.S_TONGYIBM))
                    {
                        data.S_TONGYIBM = GetUniCode((eLaiHanLX)data.I_LAIHANLX);
                        LogHelper.Instance.Log(string.Format("获取统一审批编号：{0}", data.S_TONGYIBM));
                    }
                    else
                    {
                        LogHelper.Instance.Log(string.Format("已经存在审批编号：{0}", data.S_TONGYIBM));
                    }
                    Update(data);
                    //CreateScanCode(data);
                    LogHelper.Instance.Log(string.Format("来函编号：{0}，数据处理结束", data.S_LAIHANBH));
                }
                catch (Exception e)
                {
                    LogHelper.Instance.Log("处理数据出现异常，异常信息：" + e.ToString());
                    //_HandlerData.Clear();
                    LogHelper.Instance.Log("清空处理队列信息，等待下次轮询");

                }
            }

        }
        string updateSql = "update YS_LH_LAIHANXX set s_tongyibm='{0}' where Id={1}";


        private void Update(YS_LH_LAIHANXX data)
        {
            string sql =string.Format(updateSql,data.S_TONGYIBM,(int)data.ID);
            OracleHelper.ExecuteReader(GetConn(), CommandType.Text, sql); 
        }

        private string GetUniCode(eLaiHanLX eLaiHanLX)
        {
            var ItemCode = LxDict[eLaiHanLX];
            return GovWaterApi.GovTokenHelper.GetApplyNo(ItemCode);
        }

        private void CreateScanCode(YS_LH_LAIHANXX laiHanXX)
        {
            string c_barcode_path, c_barcode_name, c_qrcode_path, c_qrcode_name;
            c_barcode_path = GetBarCode(laiHanXX.S_YONGHUM, laiHanXX.S_TONGYIBM, out c_barcode_name);

            c_qrcode_path = GetQRCode(laiHanXX.S_YONGHUM, laiHanXX.S_TONGYIBM, out c_qrcode_name);
            StringBuilder sql = new StringBuilder(@"insert YS_LH_SCANCODE(s_laihanbh
,c_unicode
,c_barcode_path
,c_barcode_name
,c_qrcode_path
,c_qrcode_name
,i_state
,d_modifydate)");
            sql.Append("values(");
            sql.Append($"'{laiHanXX.S_LAIHANBH}'");


            sql.Append($",'{laiHanXX.S_TONGYIBM}'");
            sql.Append($",'{c_barcode_path}'");
            sql.Append($",'{c_barcode_name}'");
            sql.Append($",'{c_qrcode_path}'");
            sql.Append($",'{c_qrcode_name}'");
            sql.Append($",'1', sysdate");
            sql.Append(")");
        }

        public void TestImageHandle()
        {
            string userNmae = "上海煤气第一管线工程有限公司";
            string uniCode = "001841515000424";
            string rootPath = string.Empty;
            GetQRCode(userNmae, uniCode, out rootPath);



        }
        #endregion
        #endregion
    }

}
